package proxy;

import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author: admin
 * @Description:
 * @Date: 2019/5/28 11:56
 */

public class CglibProxy implements MethodInterceptor {


    private Object target;
    public CglibProxy(){}
    public CglibProxy(Object target){this.target=target;}

    public <T> T bind(T target) {
        this.target=target;
        Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return (T)enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("--cglib--");

        System.out.println(method.getName());
        System.out.println(methodProxy.getSuperName());

        //return method.invoke(o,objects);  // error
        //return method.invoke(target,objects); // ok
        //return methodProxy.invoke(o,objects); // error
        //return methodProxy.invoke(target, objects); // ok
        return methodProxy.invokeSuper(o,objects); // ok
        //return methodProxy.invokeSuper(target,objects);// error

    }
}
